Like matrices, and lists functions are stored as ordinary variables
in the symbol table. And, like other variables in the symbol table,
functions are accessible as global variables. Function's treatment
as variables explains the somewhat peculiar syntax required to
create and store a function.
> logsin = function ( x ) { return log (x) .* sin (x); }
The above statement creates a function, and assigns it to the
variable logsin
. The function can then be used like:
> logsin ( 2 )
0.63
Like variables function can be copied, re-assigned, and destroyed.
> // Create a function
> logsin = function ( x ) { return log (x) .* sin (x); }
>> // Use it
> logsin (2)
0.63
>> // Copy it to the variable y
> y = logsin
> y (2)
0.63
>> // Overwrite it with a matrix
> logsin = rand(3,2)
logsin =
matrix columns 1 thru 2
1 0.333
0.975 0.0369
0.647 0.162
>> // Check that y still is a function
> y (2)
0.63
If you try re-assigning a built-in function you will get a run-time
error message. The built-in functions, those that are programmed in
C, are a permanent part of the environment. So that users may
always rely on their availability, they cannot be re-assigned, or
copied.
Variables that represent functions can also be part of list
objects. Sometimes it can be useful to group functions that serve a
similar purpose, or perform different parts of a larger procedure.
list = << logsin = logsin >> logsin
> list.logsin (2)
0.63
> list.expsin = function ( x ) { return exp (x) .* sin (x); }
expsin logsin
> list.expsin (2)
6.72